package com.valuegroup.smarttodo.ui.programme.weekplan;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.enums.FilterEnum;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Task;
import com.valuegroup.smarttodo.data.timeline.TimeLineModel;
import com.valuegroup.smarttodo.data.vo.TodoVo;
import com.valuegroup.smarttodo.data.vo.WeekPlanQueryParams;
import com.valuegroup.smarttodo.data.vo.WeekPlanVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.ui.todo.task.detail.TaskDetailActivity;
import com.valuegroup.smarttodo.plugins.flycotablayout.SlidingCommonTabLayout;
import com.valuegroup.smarttodo.plugins.flycotablayout.TabEntity;
import com.valuegroup.smarttodo.plugins.flycotablayout.listener.CustomTabEntity;
import com.valuegroup.smarttodo.plugins.flycotablayout.listener.OnTabSelectListener;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.recyclerview.group.GroupItemDecoration;
import com.valuegroup.smarttodo.plugins.recyclerview.group.GroupRecyclerAdapter;
import com.valuegroup.smarttodo.plugins.recyclerview.group.GroupRecyclerView;
import com.valuegroup.smarttodo.plugins.timeline.TimelineView;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 事务列表页面（时间轴方式）
 */
public class WeekTimelineActivity extends BaseActivity {

    @BindView(R.id.recycler_week_timeline_list)
    GroupRecyclerView recyclerView;
    @BindView(R.id.imgbtn_back)
    ImageButton btnBack;
    @BindView(R.id.tagExpand)
    ImageView tagExpand;
    @BindView(R.id.btnExpand)
    LinearLayout btnExpand;
    @BindView(R.id.layoutTopBar)
    LinearLayout layoutTopBar;
    @BindView(R.id.btnRange)
    SlidingCommonTabLayout btnRange;
    @BindView(R.id.btnYear)
    SlidingCommonTabLayout btnYear;
    @BindView(R.id.btnWeek)
    SlidingCommonTabLayout btnWeek;
    @BindView(R.id.btnYearSort)
    SlidingCommonTabLayout btnYearSort;
    @BindView(R.id.expandable_layout)
    ExpandableLayout expandableLayout;
    @BindView(R.id.labNowWeek)
    TextView labNowWeek;
    @BindView(R.id.splitRange)
    View splitRange;
    @BindView(R.id.splitYear)
    View splitYear;
    @BindView(R.id.splitWeek)
    View splitWeek;

    private int rangeTab, yearTab, weekTab;
    private WeekPlanQueryParams queryParams;
    private WeekTimelineAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_week_timeline);
        ButterKnife.bind(this);
        queryParams = WeekPlanQueryParams.getDefaultParams();

        initRecyclerView();
        initFilterTab();
    }


    private void initRecyclerView() {
        adapter = new WeekTimelineAdapter(this, loadData());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new GroupItemDecoration<String, TodoVo>());
        recyclerView.setAdapter(adapter);
        recyclerView.notifyDataSetChanged();
    }


    private void initFilterTab() {

        List<String> rangeTags = ServiceFactory.getInstance().getFilterService().findWeekFilterTag(FilterEnum.RANGE_WEEK, 0);
        List<String> yearTags = ServiceFactory.getInstance().getFilterService().findWeekFilterTag(FilterEnum.YEAR, 0);
        List<String> weekTags = ServiceFactory.getInstance().getFilterService().findWeekFilterTag(FilterEnum.WEEKS, queryParams.getYear());
        List<String> sortTags = ServiceFactory.getInstance().getFilterService().findWeekFilterTag(FilterEnum.SORT, 0);

        btnRange.setTabData(converTabEntity(rangeTags));
        btnYear.setTabData(converTabEntity(yearTags));
        btnWeek.setTabData(converTabEntity(weekTags));
        btnYearSort.setTabData(converTabEntity(sortTags));

        btnRange.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                btnYear.setVisibility(View.GONE);
                btnWeek.setVisibility(View.GONE);
                btnYearSort.setVisibility(View.GONE);

                splitRange.setVisibility(View.GONE);
                splitWeek.setVisibility(View.GONE);
                splitYear.setVisibility(View.GONE);

                switch (position) {
                    case 1:
                        // 指定周
                        btnYear.setVisibility(View.VISIBLE);
                        btnWeek.setVisibility(View.VISIBLE);
                        splitWeek.setVisibility(View.VISIBLE);
                        splitYear.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        // 指定年
                        btnYear.setVisibility(View.VISIBLE);
                        btnYearSort.setVisibility(View.VISIBLE);
                        splitYear.setVisibility(View.VISIBLE);
                        break;
                }
                queryParams.setRange(position);
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnYear.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                queryParams.setYear(convertVal(yearTags.get(position)));
                // 更新周
                List<String> weekTags = ServiceFactory.getInstance().getFilterService().findWeekFilterTag(FilterEnum.WEEKS, queryParams.getYear());
                btnWeek.setTabData(converTabEntity(weekTags));
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });


        btnWeek.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                List<String> weekTags = ServiceFactory.getInstance().getFilterService().findWeekFilterTag(FilterEnum.WEEKS, queryParams.getYear());
                queryParams.setWeek(convertVal(weekTags.get(position)));
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnYearSort.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                queryParams.setYearOrderAsc(convertVal(sortTags.get(position)) == 0);
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnRange.setCurrentTab(rangeTab);
        btnYear.setCurrentTab(yearTab);
        btnWeek.setCurrentTab(weekTab);

        btnYear.showDot(yearTab);
        btnWeek.showDot(weekTab);
        int color = ContextCompat.getColor(this, R.color.colorLink);
        btnYear.getMsgView(yearTab).setBackgroundColor(color);
        btnWeek.getMsgView(weekTab).setBackgroundColor(color);

        labNowWeek.setText(String.format(getResources().getString(R.string.week_plan_now_week), DateUtils.getYear(new Date()), DateUtils.getWeekOfYear(new Date())));
    }

    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.notifyDataSetChanged();
        recyclerView.smoothScrollToPosition(0);
    }

    private LinkedHashMap<String, List<WeekPlanVo>> loadData() {
        return ServiceFactory.getInstance().getEventService().findWeekPlan(queryParams);
    }

    private int convertVal(String key) {
        // 用于TAG展示(前缀+数值+后缀)#用于类型解析(数据类型)_用于类型解析(数值)
        return Integer.parseInt(key.split("#")[1].split("_")[1]);
    }

    private ArrayList<CustomTabEntity> converTabEntity(List<String> tags) {
        ArrayList<CustomTabEntity> result = new ArrayList<>();
        for (int i = 0; i < tags.size(); i++) {
            String lab = tags.get(i).split("#")[0];

            // 用于判断tab选中
            int filter = Integer.parseInt(tags.get(i).split("#")[1].split("_")[0]);
            int value = Integer.parseInt(tags.get(i).split("#")[1].split("_")[1]);
            if (FilterEnum.YEAR.getPosition() == filter && queryParams.getYear() == value) {
                yearTab = i;
            } else if (FilterEnum.WEEKS.getPosition() == filter && queryParams.getWeek() == value) {
                weekTab = i;
            }

            // 用于lab创建
            result.add(new TabEntity(lab, 0, 0));
        }
        return result;
    }

    private List<TimeLineModel> mDataList = new ArrayList<>();

    @OnClick({R.id.btnExpand, R.id.imgbtn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnExpand:
                if (expandableLayout.isExpanded()) {
                    tagExpand.setImageResource(R.drawable.ic_expand_gray3);
                    expandableLayout.collapse();
                } else {
                    expandableLayout.expand();
                    tagExpand.setImageResource(R.drawable.ic_shrink_gray3);
                }
                break;
            case R.id.imgbtn_back:
                finishAfterTransition();
                break;
        }
    }


    class WeekTimelineAdapter extends GroupRecyclerAdapter<String, WeekPlanVo> {

        private LinkedHashMap<String, List<WeekPlanVo>> map;
        private Context mContext;

        WeekTimelineAdapter(Context context, LinkedHashMap<String, List<WeekPlanVo>> map) {
            super(context);
            this.mContext = context;
            this.map = map;
            resetGroups(map, new ArrayList<>(map.keySet()));
        }

        public Context getmContext() {
            return mContext;
        }

        @Override
        public int getItemViewType(int position) {
            return TimelineView.getTimeLineViewType(position, getItemCount());
        }

        @Override
        protected RecyclerView.ViewHolder onCreateDefaultViewHolder(ViewGroup parent, int type) {
            return new TimeLineViewHolder(mInflater.inflate(R.layout.item_timeline, parent, false), type);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, WeekPlanVo item, WeekPlanVo lastItem, int position) {
            TimeLineViewHolder v = (TimeLineViewHolder) holder;
            v.initData(item, lastItem);
        }


        class TimeLineViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.timeline)
            TimelineView timeline;
            @BindView(R.id.labTitle)
            TextView labTitle;
            @BindView(R.id.labDate)
            TextView labDate;
            @BindView(R.id.labWeek)
            TextView labWeek;
            @BindView(R.id.labEventType)
            TextView labEventType;
            @BindView(R.id.tagFinish)
            TextView tagFinish;
            @BindView(R.id.tagEmoji)
            ImageView imgEmoji;
            @BindView(R.id.goDetail)
            LinearLayout goDetail;


            View itemView;

            public TimeLineViewHolder(View itemView, Integer viewType) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
                timeline.initLine(viewType);
            }


            public void initData(WeekPlanVo vo, WeekPlanVo lastVo) {

                switch (vo.getStatus()) {
                    case ACTIVE:
                        timeline.setMarker(VectorDrawableCompat.create(getmContext().getResources(), R.drawable.ic_marker_active, getmContext().getTheme()));
                        break;
                    case INACTIVE:
                        timeline.setMarker(VectorDrawableCompat.create(getmContext().getResources(), R.drawable.ic_marker_inactive, getmContext().getTheme()), R.color.colorLink);
                        break;
                    case COMPLETED:
                        timeline.setMarker(VectorDrawableCompat.create(getmContext().getResources(), R.drawable.ic_marker, getmContext().getTheme()), R.color.colorLink);
                        break;
                }

                labDate.setText(vo.getDateStr());
                labWeek.setText(vo.getWeek());
                labTitle.setText(vo.getTitle());

                // 初始化内容
                imgEmoji.setImageResource(vo.getEventType() == AppStatus.EventType.STUDY ? R.drawable.ic_study_gray3 : R.drawable.ic_event_gray3);
                imgEmoji.setColorFilter(ContextCompat.getColor(getmContext(), (vo.getEventType() == AppStatus.EventType.STUDY) ? R.color.colorAccent : R.color.colorLink));
                switch (vo.getEventType()) {
                    case AppStatus.EventType.STUDY:
                        labEventType.setText("学习");
                        break;
                    case AppStatus.EventType.GOALS_MONTH:
                        labEventType.setText("月度");
                        break;
                    case AppStatus.EventType.GOALS_QUARTER:
                        labEventType.setText("季度");
                        break;
                    case AppStatus.EventType.GOALS_YEAR:
                        labEventType.setText("年度");
                        break;
                }

                // 进入详情页
                goDetail.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Task t = ServiceFactory.getInstance().getEventService().findEventTask(vo.getId());
                        if (t != null) {
                            Intent intent = new Intent(getmContext(), TaskDetailActivity.class);
                            intent.putExtra(TaskDetailActivity.PARAMS_KEY, t.getId());
                            startActivityForResult(intent, 1006);
                        }
                    }
                });

                // 完成状态
                tagFinish.setVisibility(vo.isFinish() ? View.VISIBLE : View.GONE);

                // 和上一个项目一致的话则不显示
                boolean hideDate = lastVo != null && vo.getDateStr().equals(lastVo.getDateStr());
                labDate.setVisibility(hideDate ? View.GONE : View.VISIBLE);
                labWeek.setVisibility(hideDate ? View.GONE : View.VISIBLE);

                // 特定日期标记颜色
                int color = ContextCompat.getColor(getmContext(), R.color.textDefault);
                if (!hideDate) {
                    if (vo.getWeekNum() == 0 || vo.getWeekNum() == 6) {
                        color = ContextCompat.getColor(getmContext(), R.color.colorWeekend); // 周六日
                    } else if (!hideDate && DateUtils.compareDate(vo.getDate(), new Date()) == 0) {
                        color = ContextCompat.getColor(getmContext(), R.color.colorToday); // 当天
                    }
                }

                labDate.setTextColor(color);
                labWeek.setTextColor(color);
            }
        }
    }
}
